<script setup>
import { MeshPhysicalMaterial, MeshStandardMaterial, Vector3 } from 'three'
import { useTexture } from '@tresjs/core'
import { useGLTF } from '@tresjs/cientos'
import { dictType2GoodsModel, eastStoreMeshPositions, westStoreMeshPositions } from '@/pages/__view-constant/index'

const props = defineProps({
  eastStoreData: {
    type: Array,
    default: () => [],
  },
  westStoreData: {
    type: Array,
    default: () => [],
  },
  ready: {
    type: Boolean,
    default: false,
  },
})

// 模型加载
const { scene: modelEastStore } = await useGLTF('/models/shelf-east.gltf')
const { scene: modelWestStore } = await useGLTF('/models/shelf-west.gltf')
const modelBox = await useGLTF('/models/hw-box.gltf')
const modelBag = await useGLTF('/models/hw-bag.gltf')
const modelTray = await useGLTF('/models/hw-tray.gltf')
const modelBaffle = await useGLTF('/models/baffle.gltf')

// 贴图加载
const textureLight = await useTexture(['/texture/light.jpg'])

const textureBox = await useTexture({
  map: '/texture/box.jpg',
})
const textureBag = await useTexture({
  map: '/texture/bag.jpg',
})
const textureTray = await useTexture({
  map: '/texture/tray-min.png',
})

const textureShelf = await useTexture({
  map: '/texture/shelf.jpg',
})

const textureGlassBox = await useTexture({
  map: '/texture/glass-box.jpg',
})
const textureBoard = await useTexture({
  map: '/texture/board.jpg',
})
const textureChassis = await useTexture({
  map: '/texture/chassis.jpg',
})
const textureChassisBorder = await useTexture({
  map: '/texture/chassis-border.jpg',
})
const textureBaffle = await useTexture({
  map: '/texture/baffle.jpg',
})

const refGroupMain = shallowRef(null)
const refGroupEast = shallowRef(null)
const refGroupWest = shallowRef(null)

// 重置模型位置 start
modelBox.scene.traverse((e) => {
  if(e.type === 'Mesh') {
    e.material = new MeshPhysicalMaterial({
      reflectivity: 1,
      sheen: 1,
      map: textureBox.map,
      lightMap: textureLight,
    })
  }
  e.position.copy(new Vector3())
})

modelBag.scene.traverse((e) => {
  if(e.type === 'Mesh') {
    e.material = new MeshPhysicalMaterial({
      reflectivity: 1,
      sheen: 1,
      map: textureBag.map,
      lightMap: textureLight,
    })
  }
  e.position.copy(new Vector3())
})

let baseY = 0
modelTray.scene.traverse((e) => {
  const thisY = e.position.y

  if(baseY) {
    e.position.copy(new Vector3(0, baseY - thisY, 0))
  }
  else {
    e.position.copy(new Vector3())
  }
  if(e.type === 'Mesh') {
    // baseY = new Vector3().copy(e.position).y
    baseY === 0 && (baseY = thisY)
    e.material = new MeshPhysicalMaterial({
      reflectivity: 1,
      sheen: 1,
      map: textureTray.map,
      lightMap: textureLight,
    })
  }
})
modelBaffle.scene.traverse((e) => {
  if(e.type === 'Mesh') {
    e.material = new MeshPhysicalMaterial({
      reflectivity: 1,
      sheen: 1,
      map: textureBaffle.map,
      lightMap: textureLight,
    })
  }
  e.position.copy(new Vector3())
})
// 重置模型位置 end
const specialMeshEast = {
  // 底盘
  'Box293-04_-_Default023': {
    map: textureChassis.map,
    reflectivity: 0,
    transmission: 0.85,
    lightMap: textureLight,
  },
  'Box293-04_-_Default0234': {
    map: textureChassisBorder.map,
    lightMap: textureLight,
  },
  'Box412-04_-_Default023': {
    map: textureChassis.map,
    lightMap: textureLight,
  },
  'Box412-04_-_Default0234': {
    map: textureChassisBorder.map,
    lightMap: textureLight,
  },
  // 标识牌
  'Box413': {
    map: textureBoard.map,
    reflectivity: 1,
    lightMap: textureLight,
  },
  // 文字
  'Text003': {
    emissive: 0xFFFFFF,
    emissiveIntensity: 2,
  },
  // 障碍体
  'Box401': {
    map: textureGlassBox.map,
    reflectivity: 0.1,
    transmission: 0.6,
    lightMap: textureLight,
  },
}
const specialMeshWest = {
  // 底盘
  'Box151-04_-_Default023': {
    map: textureChassis.map,
    reflectivity: 0,
    transmission: 0.85,
    lightMap: textureLight,
  },
  'Box151-04_-_Default0234': {
    map: textureChassisBorder.map,
    lightMap: textureLight,
  },
  'Box270-04_-_Default023': {
    map: textureChassis.map,
    lightMap: textureLight,
  },
  'Box270-04_-_Default0234': {
    map: textureChassisBorder.map,
    lightMap: textureLight,
  },
  // 标识牌
  'Box292': {
    map: textureBoard.map,
    reflectivity: 1,
    lightMap: textureLight,
  },
  // 文字
  'Text002': {
    emissive: 0xFFFFFF,
    emissiveIntensity: 2,
  },
}
watch([() => refGroupEast.value, () => props.ready], ([groupEast]) => {
  if(groupEast) {
    groupEast.traverse((e) => {
      if(e.type === 'Mesh') {
        if(Object.keys(specialMeshEast).includes(e.name)) {
          e.material = e.name.includes('Text') ? new MeshStandardMaterial(specialMeshEast[e.name]) : new MeshPhysicalMaterial(specialMeshEast[e.name])
        }
        else {
          e.material = new MeshPhysicalMaterial({
            reflectivity: 1,
            sheen: 1,
            metalness: 0.05,
            map: textureShelf.map,
            lightMap: textureLight,
          })
        }
      }
    })
  }
  if(refGroupEast.value && props.ready) {
    console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '东侧货架数据及模型:', props.eastStoreData, groupEast)

    props.eastStoreData.forEach((item) => {
      let { coordinate, locationStatus, inventoryType } = item
      if(!coordinate || locationStatus === '0' || !locationStatus || !Object.keys(dictType2GoodsModel).includes(inventoryType)) {
        // 如果没有库位坐标, 库位状态为0或未知, 库位类型不在字典中, 则跳过渲染货物模型
        return
      }
      inventoryType = dictType2GoodsModel[inventoryType]

      let goodsModel = null
      switch (inventoryType) {
        case 'bag':
          goodsModel = modelBag.scene.clone()
          break
        case 'box':
          goodsModel = modelBox.scene.clone()
          break
        case 'tray':
          goodsModel = modelTray.scene.clone()
          break
        default:
          break
      }
      const [column, floor] = coordinate.split('-')
      const positionMatchKey = `target_#_${floor}-${column}`
      const { x, y, z } = eastStoreMeshPositions[positionMatchKey] || {}
      if(!x || !goodsModel) {
        return
      }
      let baffleModel = modelBaffle.scene.clone()
      baffleModel.position.copy(new Vector3(x, y, z))
      const position = new Vector3(x, y, z)
      goodsModel.position.copy(position)
      console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '东侧新加货物', goodsModel, position)
      groupEast.add(baffleModel)
      groupEast.add(goodsModel)
    })
  }
}, { immediate: true })

// 西侧库位
watch([() => refGroupWest.value, () => props.ready], ([groupWest]) => {
  if(groupWest) {
    groupWest.traverse((e) => {
      if(e.type === 'Mesh') {
        if(Object.keys(specialMeshWest).includes(e.name)) {
          e.material = e.name.includes('Text') ? new MeshStandardMaterial(specialMeshWest[e.name]) : new MeshPhysicalMaterial(specialMeshWest[e.name])
        }
        else {
          e.material = new MeshPhysicalMaterial({
            reflectivity: 1,
            sheen: 1,
            metalness: 0.04,
            map: textureShelf.map,
            lightMap: textureLight,
          })
        }
      }
    })
  }
  if(refGroupWest.value && props.ready) {
    console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '西侧货架数据及模型:', props.westStoreData, groupWest)

    props.westStoreData.forEach((item) => {
      let { coordinate, locationStatus, inventoryType } = item
      if(!coordinate || locationStatus === '0' || !locationStatus || !Object.keys(dictType2GoodsModel).includes(inventoryType)) {
        // 如果没有库位坐标, 库位状态为0或未知, 库位类型不在字典中, 则跳过渲染货物模型
        return
      }
      inventoryType = dictType2GoodsModel[inventoryType]

      let goodsModel = null
      switch (inventoryType) {
        case 'bag':
          goodsModel = modelBag.scene.clone()
          break
        case 'box':
          goodsModel = modelBox.scene.clone()
          break
        case 'tray':
          goodsModel = modelTray.scene.clone()
          break
        default:
          break
      }
      const [column, floor] = coordinate.split('-')
      const positionMatchKey = `target_#_${floor}-${column}`
      const { x, y, z } = westStoreMeshPositions[positionMatchKey] || {}
      if(!x || !goodsModel) {
        return
      }
      let baffleModel = modelBaffle.scene.clone()
      baffleModel.position.copy(new Vector3(x, y, z))
      const position = new Vector3(x, y, z)
      goodsModel.position.copy(position)
      console.log('%c%s', 'font-size:2em;background: #00965E;color: #FFF', '西侧新加货物', goodsModel, position)
      groupWest.add(baffleModel)
      groupWest.add(goodsModel)
    })
  }
}, { immediate: true })
</script>

<template>
  <TresGroup ref="refGroupMain" :position="[0, 0, 0]">
    <TresGroup ref="refGroupEast" :position="[1, -0.15, -1.25]" :rotate-x="-0.005" :rotate-z="-0.0125">
      <primitive :object="modelEastStore" />
    </TresGroup>
    <TresGroup ref="refGroupWest" :position="[-4, -0.15, 5]" :rotate-x="-0.005" :rotate-z="-0.0125">
      <primitive :object="modelWestStore" />
    </TresGroup>
  </TresGroup>
</template>

<style lang='scss' scoped>

</style>
